//全局：当前操作角色ID
var roleId="";
//角色树父节点
var zNodes =[
         	{ 
         		rname:"角色列表",
         		open:true,
         		isParent:true,
         		pkId:-1,
         		children: [
         		]
         	}
         ];
var setting = {
		view: {
			dblClickExpand: false,
			showLine: true,
			selectedMulti: false
		},
		data: {
			key: {
				name: "rname"
			},
			simpleData: {
				enable:true,
				idKey: "pkId",
				pIdKey: "pId",
				rootPId: ""
			}
		},
		callback: {
			beforeClick: function(treeId, treeNode) {
				var zTree = $.fn.zTree.getZTreeObj(treeId);
				if (treeNode.isParent) {
					zTree.expandNode(treeNode);
					return false;
				} else {
					loadRoleMessage(treeNode.pkId);
					return true;
				}
			}
		}
};
//角色用户列表
var sysRoleUserTable = function() {
	return {
		init : function() {
			var validator;
			var tableId = "sys_roleUser_table";
			util.initCheckBox(tableId);
			// 查询角色用户信息列表
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "roleId",
					"value" : roleId
				});
				aoData.push({
					"name" : "userType",
					"value" : "1"
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#sys_roleUser_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/sysRole/getRoleUser.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						return '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
					},
					"bSortable" : false
				},
				{
					"data" : "loginName",
					"bSortable" : false,
					"defaultContent" : ""
				}, {
					"data" : "trueName",
					"bSortable" : false,
					"defaultContent" : ""
				}, {
					"data" : "roleName",
					"bSortable" : false,
					"defaultContent" : ""
				}],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(tableId);
				}
			});
			
			//添加角色
			$("#role_add").click(function(e){
				$("#addRole").modal({show:true,keyboard:false});
				add_createTree();
				$('#add_role_title').text('新增角色');
			});
			
			//编辑角色
			$("#role_edit").click(function(e){
				var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
				var nodes = treeObj.getSelectedNodes();
				if(nodes.length != 0) {
					roleId = nodes[0].pkId;
				} else {
					util.showModal("#_alertModal", "请选择角色！");
					return false;
				}
				$("#addRole").modal({show:true,keyboard:false});
				$('#add_role_title').text('编辑角色');
				$.ajax({
					"type" : "post",
					"url" : "main/sysRole/getRoleInfo.mvc",
					"dataType" : "json",
					"data" : {
						"roleId" : roleId
					},
					"success" : function(resp) {
						var roleData = resp.role;
						$('#form_pkId').val(roleData.pkId);
						$('#form_roleName').val(roleData.rname);
						$('#form_roleDesc').val(roleData.rdesc);
						if (roleData.isLock == '1') {
							$("#form_isLock").parent().addClass("checked");
						} else {
							$("#form_isLock").parent().removeClass("checked");
						}
						//给树赋值
						var zNodes = resp.resTree;  
		                $.fn.zTree.init($("#add_resTreeDemo"), addsetting, zNodes);
		                if (roleData.remark) {
		                	var treeObj = $.fn.zTree.getZTreeObj("add_resTreeDemo");
						    var node=treeObj.getNodeByParam("pkId",roleData.remark, null);
						    treeObj.selectNode(node,false);
						    $("#add_parentName").attr("value", node.resName);  
					        $("#add_parentId").attr("value", node.pkId);
		                }
					}
				});
			});
			
			//锁定角色
			$("#role_lock").click(function(e){
				if (roleId=="") {
					util.showModal("#_alertModal", "请选择角色！");
					return;
				}
				if ($("#id_isLock").parent().hasClass("checked")) {
					util.showModal("#_alertModal", "该角色已被锁定！");
					return;
				}
				util.showModal("#_confirmModal", "您确定要锁定该角色？", "lock_yes");
			});
			
			//确认锁定
			$("#_confirmModal").on('click', '#lock_yes', function() {
				$.ajax({
					"type" : "post",
					"url" : "main/sysRole/lockSysRole.mvc",
					"dataType" : "json",
					"data" : {
						"roleIds" : roleId
					},
					"success" : function(resp) {
						rmsBox.notify('success', {msg: '角色已锁定'});
						loadTree();
					}
				});
			});
			
			//删除角色
			$("#role_delete").click(function(e){
				if (roleId=="") {
					util.showModal("#_alertModal", "请选择角色！");
					return;
				}
				util.showModal("#_confirmModal", "您确定要删除该角色？", "delete_role_yes");
			});
			
			//确认删除角色
			$("#_confirmModal").on('click', '#delete_role_yes', function() {
				$.ajax({
					"type" : "post",
					"url" : "main/sysRole/delSysRole.mvc",
					"dataType" : "json",
					"data" : {
						"roleIds" : roleId
					},
					"success" : function(resp) {
						rmsBox.notify('success', {msg: '角色删除成功！'});
						roleId="";
						loadTree();
					}
				});
			});
			
			//添加用户弹窗
			$("#add_user_to_role").click(function(e) {
				$("#addUserToRole").modal({show:true,keyboard:false});
				$("#user_reset").click();
				var table = $('#sys_user_select_table').DataTable();
				table.draw(true);
			});
			
			//删除选中用户
			$("#delUserFromRole").click(function(e){
				var d = [];
				d = util.getCheckedData("sys_roleUser_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择需要操作的数据！");
					return;
				}
				util.showModal("#_confirmModal", "确定从角色中删除所选用户？", "del_user_yes");
			});
			
			//确认删除选中用户
			$("#_confirmModal").on('click', '#del_user_yes', function() {
				var d = [];
				d = util.getCheckedData("sys_roleUser_table");
				var ids = [];
				for (var index=0; index<d.length; index++) {
					ids.push(d[index].pkId);
				}
				$.ajax({
					"type" : "post",
					"url" : "main/sysRole/delUserFromRole.mvc",
					"dataType" : "json",
					"data" : {
						"roleId" : roleId,
						"userIds" : ids.join(",")
					},
					"success" : function(resp) {
						var table = $('#sys_roleUser_table').DataTable();
						table.draw(true);
						rmsBox.notify('success', {msg: '删除成功！'});
					},
					"error" : function(resp) {
						rmsBox.notify('error', {msg: '删除失败！'});
					}
				});
			});
			
			//编辑角色资源
			$("#edit_resource").click(function(e){
				if (roleId == "") {
					util.showModal("#_alertModal", "请选择角色！");
					return;
				}
				$("#edit_role_resource").modal({show:true,keyboard:false});
				$.ajax({
					"type" : "post",
					"url" : "main/sysRole/getRoleResource.mvc",
					"dataType" : "json",
					"data" : {
						"roleId" : roleId
					},
					"success" : function(resp) {
						//遍历勾选
						$("#form_role_pkId").val(roleId);
						var res = resp.resIds;
						createTree(res);
					},
					"error" : function(resp) {
						rmsBox.notify('error', {msg: '获取资源列表失败！'});
					}
				});
			});
			
			//保存角色资源
			$("#form_roleres_save").click(function(e){
				var treeObj = $.fn.zTree.getZTreeObj("resTreeDemo");
				var res = treeObj.getCheckedNodes(true);
				var resIds = [];
				for (var index in res) {
					resIds.push(res[index].pkId);
				}
				$.ajax({
					"type" : "post",
					"url" : "main/sysRole/saveRoleResource.mvc",
					"dataType" : "json",
					"data" : {
						"roleId" : roleId,
						"resIds" : resIds.join(",")
					},
					"success" : function(resp) {
						$("#form_res_btn_close").click();
						rmsBox.notify('success', {msg: '资源保存成功！'});
					}
				});
			});
			
			//新增/修改角色 保存
			$("#form_role_save").click(function(e) {
				validator = validateMyForm("role_form");
				if(!validator.form()) {
					return false;
				}
				var d = {};
				d['pkId'] = $("#form_pkId").val();
				d['rname'] = $("#form_roleName").val().trim();
				d['rdesc'] = $("#form_roleDesc").val();
				d['isLock'] = $("#form_isLock").parent().hasClass("checked") ? '1':'0';
				d['homePage'] = $("#add_parentId").val();
				$.ajax({
					"type" : "post",
					"url" : "main/sysRole/saveOrUpdateSysRole.mvc",
					"dataType" : "json",
					async: false,
					"data" : d,
					"success" : function(resp) {
						if (resp.msg == 'repeat') {
							util.showModal('#_alertModal','角色已存在！');
							return;
						} else if (resp.msg == 'error') {
							rmsBox.notify('error', {msg: '修改出错！'});
							return;
						} else {
							$("#form_btn_close").click();
							rmsBox.notify('success', {msg: '保存成功！'});
						}
						loadTree();
					}
				});
			});
			
			function validateMyForm(formId){
				return $( '#' + formId ).validate({
					errorElement: 'em',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	roleName:'required',
			        	parentName:'required'
			        },
			        messages:{
			        	roleName:'不能为空',
			        	parentName:'不能为空'
			        }, 
			        errorPlacement: function (error, element) {
			        	//默认以span形式显示在输入框后
			           error.insertAfter(element);
			           $(element.next()).attr('title', $(error).text()).tooltip();
			           $(error).text('');
			        }
			    });
			};
			
			$("#form_btn_close").click(function(){
				$("#form_pkId").val('');
				$("#role_form")[0].reset();
				$("#form_isLock").parent().removeClass("checked");
				if(validator) {
					$("#role_form").validate().resetForm();
				}
			});
		}
	};
}();

var userSelectTable = function() {
	return {
		init : function() {
			var usertableId = "sys_user_select_table";
			util.initCheckBox(usertableId);
			// 查询角色用户信息列表
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "roleId",
					"value" : roleId
				});
				aoData.push({
					"name" : "keyWord",
					"value" : $("#user_userKey").val().trim()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#sys_user_select_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/sysRole/getRoleUser.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						return '<div class="checker" onclick="util.selectCheckBox(\'' + usertableId + '\', this)"><span><input type="checkbox" class="checkboxes"/></span></div>';
					},
					"bSortable" : false,
					"defaultContent" : ""
				},
				{
					"data" : "loginName",
					"bSortable" : false,
					"defaultContent" : ""
				}, {
					"data" : "realName",
					"bSortable" : false,
					"defaultContent" : ""
				}, {
					"data" : "roleName",
					"bSortable" : false,
					"defaultContent" : ""
				}],
				"fnDrawCallback" : function(oSetting) {
					util.clearSelected(usertableId);
				}
			});
			
			$("#query_user_btn").click(function(e){
				var table = $('#sys_user_select_table').DataTable();
				table.draw(true);
			});
			
			$("#user_reset").click(function(e){
				$("#user_select_form")[0].reset();
			});
			
			//保存添加的用户
			$("#add_user_for_role").click(function(e) {
				var d = [];
				d = util.getCheckedData("sys_user_select_table");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择需要操作的数据！");
					return;
				}
				var ids = [];
				for (var index=0; index<d.length; index++) {
					ids.push(d[index].pkId);
				}
				$.ajax({
					"type" : "post",
					"url" : "main/sysRole/addUsersToRole.mvc",
					"dataType" : "json",
					"data" : {
						"roleId" : roleId,
						"userIds" : ids.join(",")
					},
					"success" : function(resp) {
						$("#add_user_btn_close").click();
						var table = $('#sys_roleUser_table').DataTable();
						table.draw(true);
						rmsBox.notify('success', {msg: '用户添加成功！'});
					}
				});
			});
			
			$(function(){
				$('#query_user input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #query_user_btn').click();
					}
				});
			});
		}
	};
}();

$(document).ready(function(){
	sysRoleUserTable.init();
	loadTree();
	userSelectTable.init();
});

//在页面初始化时加载角色列表树
function loadTree () {
	// 角色列表树
	$.fn.zTree.init($("#treeDemo"), setting, zNodes);
	var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	var parentZNode = treeObj.getNodeByParam("level", 0, null); // 获取父节点
	var newNodes;
    $.ajax({
        type: 'POST',
        url: "main/sysRole/getRolesTree.mvc",
        data: { id: "0" },
        dataType: "json",
        ContentType: "application/json; charset=utf-8",
        success: function (data) {
        	newNodes = data.aaData;
        	treeObj.addNodes(parentZNode, newNodes, true);
        	// 初始化角色信息模块:默认取列表树中第一个子节点
        	if (newNodes.length==0) {
        		roleId="";
        	} else if (roleId == "" || treeObj.getNodeByParam("pkId", roleId)==null) {
        		//初次加载或当前角色已被其他用户删除，加载列表中第一个角色并默认选中
    			roleId = newNodes[0].pkId;
    		}
        	treeObj.selectNode(treeObj.getNodeByParam("pkId", roleId));
    		loadRoleMessage(roleId);
        },
        error: function (msg) {
            console.info('获取树失败');
        }
    });
}

//加载选中角色信息和用户列表
function loadRoleMessage(id) {
	$.ajax({
        type: 'POST',
        url: "main/sysRole/getRoleInfo.mvc",
        data: { "roleId": id },
        dataType: "json",
        ContentType: "application/json; charset=utf-8",
        success: function (data) {
        	var curRole = data.role;
        	if (curRole) {
        		document.getElementById("id_roleName").innerHTML  = curRole.rname;
        		document.getElementById("id_remark").innerHTML = curRole.rdesc;
        		document.getElementById("id_homePage").innerHTML = curRole.homePage;
        		$('#id_remark').attr('title', curRole.rdesc);
        		//锁定
        		if (curRole.isLock == '1') {
        			$("#id_isLock").parent().addClass("checked");
        		} else {
        			$("#id_isLock").parent().removeClass("checked");
        		}
        	} else {
        		document.getElementById("id_roleName").innerHTML = "";
        		document.getElementById("id_remark").innerHTML = '';
        		document.getElementById("id_homePage").innerHTML = '';
    			$("#id_isLock").parent().removeClass("checked");
    		}
        },
	    error: function (msg) {
	        console.info('获取角色信息失败');
	    }
	});
	//给全局变量赋值
	roleId = id;
	var table = $('#sys_roleUser_table').DataTable();
	table.draw(true);
}

//角色列表查询框实时查询
function onSearchEnter(txtObj) {
	var key = txtObj.value.trim();
	var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
	if (key == "") {
		var allNodes = treeObj.getNodesByParam("isHidden", true);
		treeObj.showNodes(allNodes);
    } else {
    	key = key.toLowerCase();
        var nodes = treeObj.getNodesByFilter(function(node){
        	return (node.level!=0);
        }, false);
    	treeObj.hideNodes(nodes);
        var nodes = treeObj.getNodesByParamFuzzy("rname", key, null);
        treeObj.showNodes(nodes);
    }
	//始终标记选中当前角色
	treeObj.selectNode(treeObj.getNodeByParam("pkId", roleId));
}
//========================================================================================
function showMenu() {
    var nameObj = $("#parentName");
    var nameOffset = $("#parentName").offset();
    $("#resContent").css({ left: 99 + "px", top: 27 + "px" }).slideDown("fast");
    $("body").bind("mousedown", onBodyDown);
}

var resSetting = {
	check: {
		enable: true,
		chkboxType: { "Y": "ps", "N": "s" }
	},
    view: {
        showLine: false,  
        dblClickExpand: true
    },
    data: {
        key : {
            name: "resName"
        },
        simpleData: {
            enable: true,
            idKey: "pkId",
            pIdKey: "parentId",
            rootPId: "0"
        }
    },
    callback: {
        beforeClick: beforeClick,
        onClick: onClick,
        onCheck: onCheck
    }
};

function createTree(resIds) {
    var zresNodes;
    $.ajax({
        type: 'POST',  
        url: "main/sysResource/getResourceTree.mvc", //url
        data: { id: "0" },
        dataType: "json",   //可以是text，如果用text，返回的结果为字符串；如果需要json格式的，可是设置为json
        ContentType: "application/json; charset=utf-8",
        success: function (data) {
        	zresNodes = data.aaData;
            $.fn.zTree.init($("#resTreeDemo"), resSetting, zresNodes);
            var treeObj = $.fn.zTree.getZTreeObj("resTreeDemo");
            if (resIds) {
            	for (var index in resIds) {
            		var node = treeObj.getNodeByParam("pkId", resIds[index]);
            		if (node) {
            			treeObj.checkNode(node,true,false);
            		}
            	}
            }
            onCheck();
        },
        error: function (msg) {
            console.info('获取树失败');
        }
    });
}

function beforeClick(treeId, treeNode) {
	return true;
}

function onClick(e, treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("resTreeDemo");
    nodes = zTree.getSelectedNodes();
	zTree.checkNode(treeNode,null,true);
	onCheck();
}
function onCheck () {
	var zTree = $.fn.zTree.getZTreeObj("resTreeDemo");
	var checkCount = zTree.getCheckedNodes(true).length;
	$("#parentName").attr("placeholder", "当前选中" + checkCount + "条资源");
}

function hideMenu() {
    $("#resContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
}
// 当点击窗口其他区域时zTree消息框隐藏 
function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "resContent" || $(event.target).parents("#resContent").length > 0)) {
        hideMenu();
    }
}


/******************资源树 resourceTree 开始******************************/
function add_showMenu() {  
    var nameObj = $("#add_parentName");  
    var nameOffset = $("#add_parentName").offset(); 
    //计算 没计算好
    $("#add_resContent").css({ left: 99 + "px", top: 27 + "px" }).slideDown("fast");  

    $("body").bind("mousedown", addonBodyDown);  
} 

var addsetting = {  
    view: {  
        showLine: false,  
        dblClickExpand: true  
    },  
    data: {  
        key : {
            name: "resName"
        },
        simpleData: {
            enable: true,  
            idKey: "pkId",  
            pIdKey: "parentId",  
            rootPId: "0"
        }  
    },  
    callback: {  
        beforeClick: beforeClick,  
        onClick: addOnClick  
    }  
};  

function add_createTree() {  
    var zNodes;  
    $.ajax({  
        type: 'POST',  
        url: "main/sysResource/getResourceTree.mvc", //url    
        data: { "id": "3" },  
        dataType: "json",   //可以是text，如果用text，返回的结果为字符串；如果需要json格式的，可是设置为json  
        ContentType: "application/json; charset=utf-8",  
        success: function (data) {  
            zNodes = data.aaData;  
            $.fn.zTree.init($("#add_resTreeDemo"), addsetting, zNodes);  
        },  
        error: function (msg) {  
            console.info('获取树失败');
        }  
    }); 
}  

function addOnClick(e, treeId, treeNode) {  
    var zTree = $.fn.zTree.getZTreeObj("add_resTreeDemo"),  
    nodes = zTree.getSelectedNodes(); 
    if(nodes[0].children != null && nodes[0].children.length>0){
    	return false;
    }else{
    	$("#add_parentName").attr("value", nodes[0].resName);  
        $("#add_parentId").attr("value", nodes[0].pkId);
        add_hideMenu();
    }
}  

function add_hideMenu() {  
    $("#add_resContent").fadeOut("fast");  
    $("body").unbind("mousedown", addonBodyDown);  
}  
// 当点击窗口其他区域时zTree消息框隐藏  
function addonBodyDown(event) {  
    if (!(event.target.id == "menuBtn" || event.target.id == "add_resContent" || $(event.target).parents("#add_resContent").length > 0)) {  
    	add_hideMenu();  
    }  
}  
   /******************资源树 resourceTree 结束******************************/
